#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

struct i18n_string_item
{
    int id;
    char text[256];
};

#define TEXT_HDetor 1
#define TEXT_IPCDev 2
#define TEXT_MDAlrm 3
static struct i18n_string_item str_array[] = 
{
    {TEXT_HDetor,"Human Detector"},
    {TEXT_IPCDev,"IPC903 Device"},
    {TEXT_MDAlrm,"MD Alarm"},
};

void i18n_generate_default(void)
{
    FILE *fp = fopen("i18n_en.dat","w");
    if(NULL == fp)
	return ;

    int i = 0;
    for(i=0;i<sizeof(str_array)/sizeof(struct i18n_string_item);i++)
    {
	char line[512]={0};
	snprintf(line,sizeof(line),"[%05d]%s\n",str_array[i].id,str_array[i].text);
	fwrite(line,1,strlen(line),fp);
    }
    fflush(fp);
    fclose(fp);
}

void i18n_init_langauage(const char *lang)
{
    if(NULL == lang)
	return ;
    char lang_file[64]={0};
    snprintf(lang_file,sizeof(lang_file),"i18n_%s.dat",lang);
    if(access(lang_file,0))
	return;
    FILE *fp = fopen(lang_file,"r");
    if(fp == NULL)
	return ;
    char *line = NULL;
    size_t len = 0;
    int readlen = 0;

    while((readlen=getline(&line,&len,fp))!=-1)
    {
	struct i18n_string_item item={0};
	sscanf(line,"[%05d]%255[^\n]",&item.id,item.text);
	int i = 0;
	for(i=0;i<sizeof(str_array)/sizeof(struct i18n_string_item);i++)
	{
	    if(item.id == str_array[i].id)
	    {
		strcpy(str_array[i].text,item.text);
	    }
	}
    }
    if(line)
	free(line);
    fclose(fp);
}

char *i18n_get_string(int id)
{
    int i = 0;

    for(i=0;i<sizeof(str_array)/sizeof(struct i18n_string_item);i++)
    {
	if(id == str_array[i].id)
	{
	    return str_array[i].text;
	}
    }
    return NULL;
}

int main(int argc, char *argv[])
{
    int ret = 0;

    i18n_generate_default();
    i18n_init_langauage("en");
    printf("HD(en) = %s\n",i18n_get_string(TEXT_HDetor));
    printf("HD(en) = %s\n",i18n_get_string(TEXT_IPCDev));
    printf("HD(en) = %s\n",i18n_get_string(TEXT_MDAlrm));

    i18n_init_langauage("cn");
    printf("HD(cn) = %s\n",i18n_get_string(TEXT_HDetor));
    printf("HD(cn) = %s\n",i18n_get_string(TEXT_IPCDev));
    printf("HD(cn) = %s\n",i18n_get_string(TEXT_MDAlrm));
    exit(0); 
}

